import { defineStore } from "pinia";
import { getUserInfo, loginOutInner, LogOut } from "@renderer/api/login";
const { ipcRenderer } = window;
interface UserStoreState {
  ifLogin: boolean;
  userInfo: any;
  showLogin: boolean;
  ifTemplateChange: boolean;
  ifCloseWindow: boolean;
}

export const useUserStore = defineStore("user", {
  state: (): UserStoreState => ({
    ifLogin: false,
    userInfo: {},
    showLogin: false,
    ifTemplateChange: false,
    ifCloseWindow: false,
  }),
  actions: {
    setLoginStatus(status: boolean) {
      this.ifLogin = status;
    },
    toggleShowLogin(val: boolean) {
      this.showLogin = val;
    },
    toggleTemplateChange(val: boolean) {
      this.ifTemplateChange = val;
    },
    toggleCloseWindow(val: boolean) {
      this.ifCloseWindow = val;
      return val;
    },

    async getUserInfo() {
      if (this.ifLogin) {
        const res: any = await getUserInfo();
        console.log(res);
        if (res.code == 200) {
          this.userInfo = res.data;
          return true;
        } else {
          this.userInfo = {};
          // ElMessage.error("获取用户信息失败");
          return false;
        }
      }
    },
    clearInfo() {
      this.userInfo = {};
      this.ifLogin = false;
      localStorage.removeItem("token");
      localStorage.removeItem("user");
      ipcRenderer.sendSync("deleteStore", "token");
    },
    async loginOut() {
      return new Promise(async (resolve, reject) => {
        try {
          let res: any = null;
          if (this.userInfo.isInner) {
            res = await loginOutInner();
          } else {
            res = await LogOut();
          }
          if (res.code == 200) {
            ElMessage.success("退出登录成功");
            this.clearInfo();
            resolve(true);
          }
        } catch (error) {
          reject(error);
        }
      });
    },
  },
  getters: {},
});
